package com.example.newhabitclock

import android.app.Application
import android.os.Build
import androidx.annotation.RequiresApi
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.viewModelScope
import com.example.newhabitclock.HabitRoomPackage.Habit
import com.example.newhabitclock.HabitRoomPackage.HabitRepository
import com.example.newhabitclock.RecordRoomPackage.CheckInRecord
import com.example.newhabitclock.ResetCheckInState.ResetCheckInWorker
import kotlinx.coroutines.launch

//外部获取viewModel对象，使用其内部封装的Room方法
@RequiresApi(Build.VERSION_CODES.O)
class MainViewModel(application: Application) : AndroidViewModel(application) {
    private val repository = HabitRepository(application)

    init {
        // 安排每日重置任务
        ResetCheckInWorker.scheduleDailyReset(application)
    }

    //val myHabitDao = repository.habitDao
    //val myCheckInRecordDao = repository.checkInRecordDao
    val allHabits: LiveData<List<Habit>> = repository.getAllHabits()

    fun insertHabit(name: String, time: String, repeatDays: List<String>) {
        viewModelScope.launch {   //autoGenerate = true,即使现在传入的id为1，后续数据库也会自动生成id将其覆盖
            repository.insertHabit(Habit(name, time, repeatDays))
        }
    }

    fun updateHabit(habit: Habit) {
        viewModelScope.launch {
            repository.updateHabit(habit)
        }
    }

    fun deleteHabit(habit: Habit) {
        viewModelScope.launch {
            repository.deleteHabit(habit)
        }
    }

    fun getHabitById(habitId: Int): LiveData<Habit> {
        return  repository.getHabitById(habitId)
    }


    //封装check_in_record表中的方法
    //插入打卡日期
    fun insertCheckInRecord(habitId: Int, date: String) {
        viewModelScope.launch {
            repository.insertCheckInRecord(CheckInRecord(habitId, date))
        }
    }

    //通过该习惯id找到对应习惯的所有打卡日期
    fun getCheckInDates(habitId: Int): LiveData<List<String>> {
        return repository.getCheckInDates(habitId)
    }
}